package cre.tomcat.ch02;

import cre.tomcat.ch02.processor.ServletProcessor2;
import cre.tomcat.ch02.processor.StaticResourceProcessor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import static cre.tomcat.ch02.Constant.SHUT_DOWN;

/**
 * @Author penglai
 * @Date 2016/12/29.
 */
public class HttpServer2 {

    public static void main(String[] args) {
        HttpServer2 server = new HttpServer2();
        server.await();
    }

    private void await() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080, 100, InetAddress.getByName("127.0.0.1"));
            System.out.println("httpServer2 start...");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        boolean shutdown = false;
        while (!shutdown) {
            try {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                Request request = new Request(inputStream);
                request.parse();

                Response response = new Response(outputStream);
                response.setRequest(request);

                //check request type
                if (request.getUri().startsWith("/servlet/")) {
                    ServletProcessor2 processor = new ServletProcessor2();
                    processor.process(request, response);
                } else {
                    StaticResourceProcessor processor = new StaticResourceProcessor();
                    processor.process(request, response);
                }

                socket.close();
                shutdown = request.getUri().equals(SHUT_DOWN);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}
